C language char* and char[] usage difference analysis
- 2020-04-02 02:46:01
- OfStack
This article illustrates the difference between char* and char [] in C. Share with you for your reference. Specific analysis is as follows:
In general, a lot of people think that these two definitions are the same, but they're very different. The following are some personal opinions, which are not correct.
Essentially, a char *s defines a pointer to a char that knows only the memory unit it is pointing to and not the size of the memory unit.
When char *s = "hello"; After, you cannot use s[0]='a'; Statement for assignment. This will prompt that the memory cannot be "written".
When use char [] s = "hello"; S [0]='a'; Assign values. This is a regular array operation.
If the definition:
char s[] = "hello";
char *p = s;
You can also use p[0] = 'a'; Because this is p ==s, all Pointers to the array.
Here's another definition:
char *s = (char *)malloc(n(www.jb51.net));//Where n is the size of the space to be created
This is the equivalent of:
char s[n];
Also defines a pointer to an array to perform subscript operations on the array
example
#include <stdio.h>
int main(int argc, char* argv[]) {
char* buf1 = "this is a test";
char buf2[] = "this is a test";
printf("size of buf1: %dn", sizeof(buf1));
printf("size of buf2: %dn", sizeof(buf2));
return 0;
}
The result is:
$
>
. / the main
The size of buf1:4
The size of buf2:15
I believe that this article has certain reference value to the learning of C programming language.